/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.service.impl;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.domain.DataBean;
import com.koron.common.web.Util;
import com.koron.report.bean.CheckRecordAnalysis;
import com.koron.report.mapper.DataAnalysisMapper;
import com.koron.report.service.api.DangerAnalysisService;
import com.koron.report.service.api.SafetyCheckRecordAnalyService;
import com.koron.report.util.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SafetyCheckRecordAnalyServiceImpl implements SafetyCheckRecordAnalyService {

    private final static  Logger logger= LoggerFactory.getLogger(SafetyCheckRecordAnalyServiceImpl.class);

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private DangerAnalysisService dangerAnalysisService;

    @Autowired
    private Util util;

    @Override
    public MessageBean<DataBean<CheckRecordAnalysis>> getSafetyCheckRecordAnalysisListByLevel(Integer orgLevel, String orgCode, Date startTime, Date endTime, Integer page, Integer pageSize) {
        MessageBean<DataBean<CheckRecordAnalysis>> msg=new MessageBean<>();
        try(SessionFactory factory=new SessionFactory()){
            Map<String,String> map=dangerAnalysisService.getAnalysisDateMap();
            List<CheckRecordAnalysis> analysisList=new ArrayList<>();
            switch (orgLevel){
                case 0:
                   msg=getSafetyCheckRecordAnalysisListByCorp(startTime, endTime, page, pageSize);
                   return msg;
                case 1:
                    //水司
                    //判断是否是粤海水务
                    if("7962a1fbd61a4bbe9361b9942bdfc0cb".equals(orgCode)){
                      //粤海水务，返回粤海水务下所有水司的统计数据
                        List<DepartmentTreeBean> departmentTreeBeanList1= (List<DepartmentTreeBean>) util.depttree("7962a1fbd61a4bbe9361b9942bdfc0cb",0).getData();
                        //获取已开通的水司列表
                        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
                        List<String> realCorpCodeList=new ArrayList<>();
                        if (null!=corpBeanList)
                            realCorpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
                        if(null!=departmentTreeBeanList1&&departmentTreeBeanList1.size()>0){
                           for(int i=1;i<departmentTreeBeanList1.size();i++){
                               DepartmentTreeBean departmentTreeBean=departmentTreeBeanList1.get(i);
                               //未开通或者非水司，跳过
                               if (!realCorpCodeList.contains(departmentTreeBean.getDepartmentCode()))
                                   continue;
                               List<String> corpCodeList2=new ArrayList<>();
                               corpCodeList2.add(departmentTreeBean.getDepartmentCode());
                               CheckRecordAnalysis checkRecordAnalysis3=factory.getMapper(DataAnalysisMapper.class).queryCountCheckRecord(map.get("groupClass"),
                                       map.get("plateClass"),map.get("departmnetClass"),map.get("departmnetClass"),startTime,endTime,corpCodeList2);
                               if (checkRecordAnalysis3==null)
                                   checkRecordAnalysis3=new CheckRecordAnalysis();
                               checkRecordAnalysis3.setDepartmentCode(departmentTreeBean.getDepartmentCode());
                               checkRecordAnalysis3.setDepartmentName(departmentTreeBean.getName());
                               analysisList.add(checkRecordAnalysis3);
                           }
                        }
                    }else{
                        //一般水司
                        CorpBean corpBean=corpManagementService.getOne(orgCode).getData();
                        //判断层级已做了非空判断，此处不需要
                        analysisList=factory.getMapper(DataAnalysisMapper.class).queryCountCheckRecordListByGrid(map.get("groupClass"),
                                map.get("plateClass"),map.get("departmnetClass"),map.get("departmnetClass"),startTime,endTime,corpBean.getCorpCode());
                    }
                    break;
                default:
                    break;
            }
            if(analysisList!=null&&analysisList.size()>0){
                Integer totalNumber=analysisList.size();
                pageSize=pageSize==null||pageSize<=0?totalNumber:pageSize;
                Integer start=0,end=15,totalPage=1;
                if(page!=null&&page>1){
                    if(pageSize==null||pageSize<=0){
                        pageSize=15;
                    }
                    start=(page-1)*pageSize;
                    end=start+pageSize;
                }
                if (end>totalNumber){
                    end=totalNumber;
                    if (start>end){
                        start=end;
                    }
                    totalPage = totalNumber / pageSize + 1;
                }
                DataBean<CheckRecordAnalysis> dataBean=new DataBean<>();
                dataBean.setPageSize(pageSize);
                dataBean.setPageNo(page);
                dataBean.setTotalPage(totalPage);
                dataBean.setTotalNumber(totalNumber);
                dataBean.setList(analysisList.subList(start,end));
                msg.setData(dataBean);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            return msg;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<CheckRecordAnalysis>>  getSafetyCheckRecordAnalysisListByCorp(Date startTime, Date endTime, Integer page, Integer pageSize) {
        MessageBean<DataBean<CheckRecordAnalysis>> msg=new MessageBean<>();
        try(SessionFactory factory=new SessionFactory()){
            Map<String,String> map=dangerAnalysisService.getAnalysisDateMap();
            List<CheckRecordAnalysis> analysisList=new ArrayList<>();
            //获取所有已开通的水司列表
            List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
            if(null!=corpBeanList&&corpBeanList.size()>0){
                for(CorpBean corpBean:corpBeanList){
                    List<String> corpCodeList=new ArrayList<>();
                    corpCodeList.add(corpBean.getCorpCode());
                    CheckRecordAnalysis checkRecordAnalysis3=factory.getMapper(DataAnalysisMapper.class).queryCountCheckRecord(map.get("groupClass"),
                            map.get("plateClass"),map.get("departmnetClass"),map.get("departmnetClass"),startTime,endTime,corpCodeList);
                    if (checkRecordAnalysis3==null)
                        checkRecordAnalysis3=new CheckRecordAnalysis();
                    checkRecordAnalysis3.setDepartmentCode(corpBean.getCorpCode());
                    checkRecordAnalysis3.setDepartmentName(corpBean.getCorpName());
                    analysisList.add(checkRecordAnalysis3);
                }
            }
            if(analysisList!=null&&analysisList.size()>0){
                Integer totalNumber=analysisList.size();
                pageSize=pageSize==null||pageSize<=0?totalNumber:pageSize;
                Integer start=0,end=15,totalPage=1;
                if(page!=null&&page>1){
                    if(pageSize==null||pageSize<=0){
                        pageSize=15;
                    }
                    start=(page-1)*pageSize;
                    end=start+pageSize;
                }
                if (end>totalNumber){
                    end=totalNumber;
                    if (start>end){
                        start=end;
                    }
                    totalPage = totalNumber / pageSize + 1;
                }
                DataBean<CheckRecordAnalysis> dataBean=new DataBean<>();
                dataBean.setPageSize(pageSize);
                dataBean.setPageNo(page);
                dataBean.setTotalPage(totalPage);
                dataBean.setTotalNumber(totalNumber);
                dataBean.setList(analysisList.subList(start,end));
                msg.setData(dataBean);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            return msg;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }
}
